package com.quanyan.user.service.impl;

import com.google.common.base.Function;
import com.google.common.collect.ImmutableMultiset;
import com.google.common.collect.Lists;
import com.lefu.commons.utils.Page;
import com.quanyan.api.APIResponse;
import com.quanyan.comment.response.LableBaseInfo;
import com.quanyan.comment.serviceFacade.CommentServiceFacade;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.user.mapper.NewsDetailMapper;
import com.quanyan.user.mapper.NewsTopicMapper;
import com.quanyan.user.model.vo.request.ReqCommentQuery;
import com.quanyan.user.model.vo.response.RespTopic;
import com.quanyan.user.model.vo.response.RespTopicListInfo;
import com.quanyan.user.model.vo.response.TbTopicHost;
import com.quanyan.user.request.ReqNewsTopic;
import com.quanyan.user.response.RespNewsTopic;
import com.quanyan.user.service.TopicService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/11/22.
 */
@Service
public class TopicServiceImpl implements TopicService {

   private static final Logger logger = LoggerFactory.getLogger(TopicServiceImpl.class);

   @Autowired
   private NewsTopicMapper newsTopicMapper;

   @Autowired
   private NewsDetailMapper newsDetailMapper;

    @Value("${topic.h5.share.url}")
    private String topicShareUrl;

    @Autowired
    private CommentServiceFacade commentServiceFacade;


   @Override
   public APIResponse getForwardTopicList(ReqCommentQuery reqCommentQuery){
      Page<List<RespTopicListInfo>> page = this.findAllPage(reqCommentQuery);
      PageObj<List<RespTopicListInfo>> result = PageObj.create(page.getTotalResult(), page.getCurrentPage(), page.getShowCount(), page.getObject());
      return APIResponse.returnSuccess(result);
   }


    public PageObj<List<RespNewsTopic>> findAllTopic(ReqNewsTopic reqNewsTopic){
       Page page = new Page();
       int pageIndex = reqNewsTopic.getPageNo() + 1;
       page.setCurrentPage(pageIndex);
       page.setShowCount(reqNewsTopic.getPageSize());
       List<RespNewsTopic> lstResult = newsTopicMapper.findAllNewsTopic(page,reqNewsTopic);
       try {
          if( pageIndex > page.getTotalPage()){// 大于最后一页
             lstResult = new ArrayList<>();
             page.setTotalPage(0);
             page.setTotalResult(0);
             page.setCurrentResult(0);
          }
          PageObj<List<RespNewsTopic>> result = PageObj.create(page.getTotalResult(), page.getCurrentPage(), page.getShowCount(), lstResult);
          return result;
       } catch (Exception e) {
          logger.error("",e);
          return null;
       }

    }

   public Page<List<RespTopicListInfo>> findAllPage(ReqCommentQuery reqCommentQuery){
      Page page = new Page();
      int pageIndex = reqCommentQuery.getPageNum() + 1;
      page.setCurrentPage(pageIndex);
      page.setShowCount(reqCommentQuery.getPageSize());
      List<RespTopic> lstResult =  newsTopicMapper.findAllTopicList(page);
      List<RespTopicListInfo> result = new ArrayList<>();
      if (pageIndex > page.getTotalPage() ){
         lstResult = new ArrayList<>();
         page.setTotalResult(0);
         page.setTotalPage(0);
      }
        List<Integer> lstTopicId = new ArrayList<>();
        lstTopicId.addAll(this.listRespTopicToListId(lstResult));
        List<TbTopicHost> lstTopicHot = null;
        if(lstTopicId.size() > 0)
            lstTopicHot =  newsDetailMapper.queryTopicsHot(lstTopicId);

      if (lstResult != null && lstResult.size() > 0){
         for (RespTopic respTopic : lstResult ){
            RespTopicListInfo respTopicListInfo = new RespTopicListInfo();
            respTopicListInfo.setPep_total(respTopic.getPep_total());
            respTopicListInfo.setReply_total(respTopic.getReply_total());
            respTopicListInfo.setTopic(respTopic);
             respTopicListInfo.setShareUrl(this.topicShareUrl + respTopic.getId());
            for (TbTopicHost tbTopicHost : lstTopicHot){
                if (tbTopicHost.getTopicId().intValue() == respTopic.getId().intValue()){
                    int tempSum = tbTopicHost.getSumHot().intValue() + respTopic.getReply_total().intValue();
                    respTopicListInfo.setTotalCountHot(tempSum);
                    break;
                }
            }
            result.add(respTopicListInfo);
         }
      }
      page.setObject(result);
      return page;
   }

    @Override
    public APIResponse<RespTopicListInfo> queryTopicDetail(Integer topicId) {
        if(topicId == null)
            return APIResponse.returnFail("topicId不能为空!");
        try {
            RespTopicListInfo respTopicListInfo = new RespTopicListInfo();
            RespTopic respTopic = newsTopicMapper.findDetailTopic(topicId);
            if(respTopic != null){
                List<Integer> listTopicId = new ArrayList<>();
                listTopicId.add(respTopic.getId());
                respTopicListInfo.setPep_total(respTopic.getPep_total());
                respTopicListInfo.setReply_total(respTopic.getReply_total());
                respTopicListInfo.setTopic(respTopic);
                respTopicListInfo.setShareUrl(this.topicShareUrl + topicId);
                if(listTopicId.size() > 0){
                    List<TbTopicHost> lstTopicHot =  newsDetailMapper.queryTopicsHot(listTopicId);
                    if(lstTopicHot != null && lstTopicHot.size() > 0){
                        TbTopicHost tbTopicHost =  lstTopicHot.get(0);
                        int tempSum = tbTopicHost.getSumHot().intValue() + respTopic.getReply_total().intValue();
                        respTopicListInfo.setTotalCountHot(tempSum);
                    }
                }
                return APIResponse.returnSuccess(respTopicListInfo);
            }
            return APIResponse.returnFail("该话题不存在!");

        } catch (Exception e) {
            logger.error("{}",e);
            return APIResponse.returnFail("系统异常");
        }
    }


    //list 按属性生成一个新的 list
    public ImmutableMultiset<Integer> listRespTopicToListId(List<RespTopic> list) {
        return ImmutableMultiset.copyOf(Lists.transform(list, new Function<RespTopic, Integer>() {
                    @Override
                    public Integer apply(RespTopic input) {
                        return input.getId();
                    }
                }
        ));
    }

    public APIResponse<List<RespTopicListInfo>> batchTopic(List<Integer> lstTopicId){
        if (lstTopicId == null && lstTopicId.size() < 1)
            return APIResponse.returnFail("请输入参数!");
        logger.info("批量查话题详情 {}",lstTopicId.toString());
        List<RespTopicListInfo> result = new ArrayList<>();
        try {
            List<RespTopic> lstResult = newsTopicMapper.findDetailTopicBatch(lstTopicId);
            List<TbTopicHost> lstTopicHot = null;
            if(lstTopicId.size() > 0)
                lstTopicHot =  newsDetailMapper.queryTopicsHot(lstTopicId);

            List<Integer> labelIds = new ArrayList<>();
            List<LableBaseInfo> lableBaseInfoList  = new ArrayList<>();
            labelIds.addAll(this.coverListByPropertyScenesLabel(lstResult));

            if (labelIds.size() > 0){
                try {
                    lableBaseInfoList  = commentServiceFacade.batchTagByIds(labelIds);
                    //tbSysLabelList = sysLabelService.batchLabelByIds(labelIds);
                } catch (Exception e) {
                    logger.error("查询标签失败{}",e);
                }
            }

            if (lstResult != null && lstResult.size() > 0){
                for (RespTopic respTopic : lstResult ){
                    RespTopicListInfo respTopicListInfo = new RespTopicListInfo();
                    respTopicListInfo.setPep_total(respTopic.getPep_total());
                    respTopicListInfo.setReply_total(respTopic.getReply_total());
                    respTopicListInfo.setTopic(respTopic);
                    respTopicListInfo.setShareUrl(this.topicShareUrl + respTopic.getId());

                    for (LableBaseInfo lableBaseInfo : lableBaseInfoList){
                        if (lableBaseInfo.getId().intValue() == respTopic.getScenesLabel().intValue()){
                            respTopic.getLabels().add(lableBaseInfo.getText());
                        }
                    }

                    for (TbTopicHost tbTopicHost : lstTopicHot){
                        if (tbTopicHost.getTopicId().intValue() == respTopic.getId().intValue()){
                            int tempSum = tbTopicHost.getSumHot().intValue() + respTopic.getReply_total().intValue();
                            respTopicListInfo.setTotalCountHot(tempSum);
                            break;
                        }
                    }
                    result.add(respTopicListInfo);
                }
            }
        } catch (Exception e) {
            logger.error("",e);
        }
        logger.info("批量查话题详情结束 {}",result.toString());
        return APIResponse.returnSuccess(result) ;

    }

    //list 按属性生成一个新的 list
    public ImmutableMultiset<Integer> coverListByPropertyScenesLabel(List<RespTopic> lst) {
        return ImmutableMultiset.copyOf(Lists.transform(lst, new Function<RespTopic, Integer>() {
                    @Override
                    public Integer apply(RespTopic input) {
                        return input.getScenesLabel();
                    }
                }
        ));
    }

}
